// 定义烟花粒子
class Particle {
  constructor(x, y, vx, vy, color, canvas) {
    this.x = x;
    this.y = y;
    this.vx = vx;
    this.vy = vy;
    this.color = color;
    this.canvas = canvas;
    this.alpha = 1;
  }

  // 更新粒子状态
  update() {
    this.x += this.vx;
    this.y += this.vy;
    this.vy += 0.1; // 加速度
    this.alpha -= 0.01; // 淡化颜色
  }

  // 绘制粒子
  draw() {
    const ctx = this.canvas.getContext("2d");
    ctx.globalAlpha = this.alpha;
    ctx.fillStyle = this.color;
    ctx.fillRect(this.x, this.y, 4, 4);
  }
}
// 创建一个烟花粒子爆炸效果
function explode(x, y, canvas, particles) {
  const ctx = canvas.getContext("2d");
  // 创建一定数量的小粒子
  for (let i = 0; i < 30; i++) {
    const speed = Math.random() * 3 + 2;
    const angle = Math.random() * Math.PI * 2;
    const vx = Math.cos(angle) * speed;
    const vy = Math.sin(angle) * speed;
    const color = `hsl(${Math.random() * 360}, 100%, 50%)`;
    particles.push(new Particle(x, y, vx, vy, color, canvas));
  }

  // 每一帧更新粒子状态，并绘制到Canvas上
  function loop() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // 清除画布
    for (const particle of particles) {
      particle.update();
      particle.draw();
    }
    particles = particles.filter((particle) => particle.alpha > 0); // 移除已经淡化的粒子
    requestAnimationFrame(loop); // 继续更新下一帧
  }
  // 开始循环更新粒子状态
  loop();
}
/**
 * 鼠标点击动画
 */
class MouseClickAnimation {
  constructor() {
    this.canvas = null;
    // 当前显示的球数组
    this.circles = [];
    this.createCanvas();
  }
  // 创建一个canvas
  createCanvas() {
    this.canvas = document.createElement("canvas");
    this.canvas.width = window.screen.width;
    this.canvas.height = window.screen.height;
    this.canvas.style.position = "fixed";
    this.canvas.style.top = "0";
    this.canvas.style.left = "0";
    this.canvas.style.zIndex = "9999";
    this.canvas.style.pointerEvents = "none";
    document.body.appendChild(this.canvas);
    this.windowClick();
  }
  // 监听window点击事件(因为canvas被禁止了事件，所以用window监听事件)
  windowClick() {
    window.addEventListener("mousedown", (e) => {
      explode(e.clientX, e.clientY, this.canvas, this.circles);
    });
  }
}

new MouseClickAnimation();
